package ysq.xyg.base.filter;

import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.ArrayList;
import java.util.List;

/**
 * Xss过滤对象
 *
 * @author shengQiang yu
 * @date 2019-04-08 20:17
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper{

    public static List<String> paramsList = new ArrayList<String>();

    public XssHttpServletRequestWrapper(HttpServletRequest request){
        super(request);
    }


    @Override
    public String[] getParameterValues(String name){
        String[] values = super.getParameterValues(name);
        if (values != null && !checkParams(name))
        {
            int length = values.length;
            String[] escapseValues = new String[length];
            initParams();
            for (int i = 0; i < length; i++){
                // 防xss攻击和过滤前后空格
                escapseValues[i] = Jsoup.clean(values[i], Whitelist.relaxed()).trim();
            }
            return escapseValues;
        }
        return super.getParameterValues(name);
    }


    public boolean checkParams(String name){

        for (String params : paramsList) {
            if (params.equals(name)) {
                return true;
            }
        }
        return false;
    }

    public void initParams(){
        paramsList.add("content");
    }

}